package org.shiro.demo.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Category;
import org.shiro.demo.entity.Group;
import org.shiro.demo.entity.Product;
import org.shiro.demo.entity.ProductWithGroup;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IGroupService;
import org.shiro.demo.service.IProductService;
import org.shiro.demo.util.ProductOrder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 团类别详情
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/group")
public class GroupController {

	@Resource(name = "groupService")
	IGroupService groupService;

	@Resource(name = "baseService")
	IBaseService baseService;

	/***
	 * 查找所有的团
	 * 
	 * @return
	 */
	@RequestMapping("/all")
	@ResponseBody
	public List<Group> all() {
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("status", QueryCondition.EQ, true));
		List<Group> groups = groupService.get(Group.class, queryConditions);
		return groups;
	}

	/**
	 * 新增团
	 * 
	 * 判断 团是否存在
	 * 
	 * @param status
	 *            是否激活。。新增团一定是非激活的
	 * @param productId
	 *            产品id
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("/add")
	@RequiresAuthentication
	@RequiresRoles("group-chief")
	@ResponseBody
	public Object addGroup(@RequestParam(value = "productId", required = true) long productId,String description,int personAmount, double personPrice, int balance, String deadline, String image) throws ParseException {
		ResponseResult rr = new ResponseResult();

		Product product = baseService.getById(Product.class, productId);
		if (product == null) {
			rr.setCode(0);
			rr.setInfo("产品不存在");
			return rr;
		}
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("product", QueryCondition.EQ, product));
		queryConditions.add(new QueryCondition("personAmount", QueryCondition.EQ, personAmount));

		Group oldgroup = (Group) baseService.getSingleResult(Group.class, queryConditions);

		if (oldgroup != null) {
			rr.setCode(0);
			rr.setInfo("该团已存在");
			return rr;
		}
		if (personPrice > product.getPrice()) {
			rr.setCode(0);
			rr.setInfo("团价不能高于正常价");
			return rr;
		}
		if (personAmount <= 1) {
			rr.setCode(0);
			rr.setInfo("团员数量太少");
			return rr;
		}
		Group group = new Group();// 新建团
		group.setProduct(product);
		group.setStatus(false);
		group.setBalance(balance);
		group.setPersonAmount(personAmount);
		group.setPersonPrice(personPrice);
		group.setImage(image);// 团海报
		group.setDescription(description);
		group.setProductId(productId);
		group.setVersion(1);
		
		if (deadline != null) {
			SimpleDateFormat sim = new SimpleDateFormat("yy-MM-dd");
			Date deadlineDay = sim.parse(deadline);
			group.setDeadline(deadlineDay);
		}
		try {
			groupService.save(group);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	/**
	 * 修改团
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/modify")
	@RequiresAuthentication
	@RequiresRoles("group-chief")
	@ResponseBody
	public Object modify(@RequestParam(value="groupId")long groupId,@RequestParam(value="deadline") String deadline,@RequestParam(value="personPrice") double personPrice,@RequestParam(value="balance")int balance,@RequestParam(value="version")int version) {
		ResponseResult rr = new ResponseResult();

		// 只能修改 时间，价格 跟 货存。 其他不行

		Group groupinDb = baseService.getById(Group.class, groupId);
		
		if ( personPrice > groupinDb.getProduct().getPrice()) {
			rr.setCode(0);
			rr.setInfo("团价不能高于正常价");
			return rr;
		}
		
		try {
			groupinDb.setPersonPrice(personPrice);
			
			SimpleDateFormat sim = new SimpleDateFormat("yy-MM-dd");
			Date deadlineDay = sim.parse(deadline);
			groupinDb.setDeadline(deadlineDay);
			groupinDb.setBalance(balance);
			groupinDb.setVersion(version);

			groupService.update(groupinDb);
			
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;

	}

	/**
	 * 激活团
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/activate")
	@RequiresAuthentication
	@RequiresRoles("group-chief")
	@ResponseBody
	public Object activate(long groupId) {
		ResponseResult rr = new ResponseResult();

		// 只能修改 时间，价格 跟 货存。 其他不行

		Group groupinDb = baseService.getById(Group.class, groupId);

		try {
			if (groupinDb.getStatus() == false) {
				groupinDb.setStatus(true);
				groupService.update(groupinDb);
			}

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;

	}

	/**
	 * 关闭团
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/deactivate")
	@RequiresAuthentication
	@RequiresRoles("group-chief")
	@ResponseBody
	public Object deactivate(long groupId) {
		ResponseResult rr = new ResponseResult();

		// 只能修改 时间，价格 跟 货存。 其他不行

		Group groupinDb = baseService.getById(Group.class, groupId);

		try {
			if (groupinDb.getStatus() == true) {
				groupinDb.setStatus(false);
				groupService.update(groupinDb);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	/**
	 * 团详情。。根据product 找 多个 团 详情
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/detailsByPid")
	@ResponseBody
	public Object detailsByPid(long productId) {
		ResponseResult rr = new ResponseResult();
		Product product = baseService.getById(Product.class, productId);
		// 只能修改 时间，价格 跟 货存。 其他不行

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("product", QueryCondition.EQ, product));
		queryConditions.add(new QueryCondition("status", QueryCondition.EQ, true));
		List<Group> groups = baseService.get(Group.class, queryConditions);

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(groups);
		return rr;
	}

	/**
	 * 团详情。。根据gid 找 多个 团 详情
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/detailsByGid")
	@ResponseBody
	public Object detailsByGid(long groupId) {
		ResponseResult rr = new ResponseResult();

		Group group = baseService.getById(Group.class, groupId);

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(group);
		return rr;
	}

	/**
	 * 删除团
	 * 
	 * @param group
	 *            团
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresAuthentication
	@RequiresRoles("group-chief")
	@ResponseBody
	public Object delete(long groupId) {
		ResponseResult rr = new ResponseResult();
		try {
			baseService.delete(Group.class, groupId);
			rr.setCode(1);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
		}
		return rr;
	}

	@Resource(name = "productService")
	private IProductService productService;

	/**
	 * 根据产品类别拿产品///产品信息中带着团信息
	 * 
	 * @param categoryId
	 * @return
	 */
	@RequestMapping(value = "/listbycid")
	public @ResponseBody List<ProductWithGroup> getProductsByCategoryid(@RequestParam(value = "categoryId") long categoryId, @RequestParam(value = "order", required = false) String orderName) {

		Category category = baseService.getById(Category.class, categoryId);
		if (null != category) {
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			QueryCondition queryCondition = new QueryCondition("category", QueryCondition.EQ, category);
			list.add(queryCondition);
			ProductOrder productOrder = null;
			if (orderName != null)
				productOrder = ProductOrder.valueOf(orderName);
			else
				productOrder = ProductOrder.newest;

			String order;
			switch (productOrder) {
			case hot:
				order = productOrder.getText();
				break;
			case newest:
				order = productOrder.getText();
				break;
			case highprice:
				order = productOrder.getText();
				break;
			case lowerprice:
				order = productOrder.getText();
				break;
			default:
				order = "modifyDate DESC";
				break;
			}
			List<ProductWithGroup> productWithGroups = new ArrayList<ProductWithGroup>();
			List<Product> products = productService.get(Product.class, list, "ORDER BY o." + order);
			for (Product p : products) {
				ProductWithGroup pwg = new ProductWithGroup();
				List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
				queryConditions.add(new QueryCondition("product", QueryCondition.EQ, p));
				List<Group> groups = baseService.get(Group.class, queryConditions);
				StringBuilder sb = new StringBuilder();
				for (Group g : groups) {
					sb.append(g.getId() + "_" + g.getPersonAmount() + "_" + g.getStatus() +"_" + g.getVersion()+  ";");
				}
				pwg.setProduct(p);
				String str = sb.toString();
				if (!StringUtils.isEmpty(str)) {
					pwg.setGroups(str.substring(0, str.length() - 1));
				}
				productWithGroups.add(pwg);
			}

			return productWithGroups;
		}
		return null;
	}
}
